<?php
/**
 * Storage handler object.
 * @author Gustav Knutsson
 */
class jdStorage{
	// Database object
	private $jddb;
	
	// Holds the jdNetworkMeta object
	protected $jdnm;
	
	/**
	 * Class construct...
	 */
	public function __construct(){
		$this->jddb = jdDatabaseMySql::getInstance();
		$this->jdnm = new jdNetworkMeta();
	}
	
	/**
	 * Stores the file in the storage
	 * 
	 * @param STRING $filedata
	 * @param STRING $filename
	 * @param STRING $user_id
	 * @return bool
	 * 
	 * @author Gustav Knutsson
	 * @access public
	 */
	public function Store($filedata, $filename, $user_id){
		// Save the file in the database, to get the ID
		$this->jddb->statement("
		INSERT INTO files
		(f_name, f_userID, f_storedate)
		VALUES
		('".mysql_real_escape_string($filename)."','".mysql_real_escape_string($user_id)."','".date("Y-m-d H:i:s")."')");
		
		$f_id = $this->jddb->LAST_ID;
		
		$this->_save($f_id, $filedata);
	}
	
	/**
	 * Saves the file directly to the storage.
	 * 
	 * @param STRING $filedata
	 * @param STRING $filename
	 * 
	 * @author Gustav Knutsson
	 * @access public
	 */
	public function NodeStore($filedata, $filename){
		$this->_save($filename, $filedata);
	}
	
	/**
	 * Updates information on a specific file in the database to be node handled.
	 * 
	 * @param INT $node_id
	 * @param INT $file_id
	 * @author Gustav Knutsson
	 */
	private function _setNodeSave($node_id, $file_id){
		$this->jddb->statement("UPDATE files SET f_nodeID = '".$node_id."' WHERE f_id = '".$file_id."'");
	}
	
	/**
	 * Saves the data on the filesystem.
	 * 
	 * @param INT $fileid
	 * @param STRING $filedata
	 * 
	 * @author Gustav Knutsson
	 */
	private function _save($fileid, $filedata){
		$nodes = $this->jdnm->getNodeList();
		if(count($nodes) > 0){
			// Think about redistributing...
			$nid = $this->jdnm->getNextNode();
			if($nid == 0){
				$file = new Filewriter($fileid, $filedata);
			}else{
				// Redistribute the file to a slave.
				$jddfs = new jdDFS();
				$jddfs->SaveToNode($nid, $fileid, $filedata);
				
				// Update the file with the new info.
				$this->_setNodeSave($nid, $fileid);
			}
		}else{
			$file = new Filewriter($fileid, $filedata);
		}
	}
}
?>